//
//  WmcCreateTagVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/17.
//

import UIKit
import YPBedrock

extension WmcCreateTagVC {
    enum Mode {
        case add
        case edit(tagView: WmcBaseTagView)
    }
}

// MARK: - [WmcCreateTagVC]

class WmcCreateTagVC: WmcBaseVC {
    // Lifecycle

    init(mode: Mode) {
        super.init(nibName: nil, bundle: nil)
        self.mode = mode

        switch self.mode {
        case .add:
            switchTagStyle(.textHookEdge)

        case let .edit(tagView: tagView):
            self.currentTagView = tagView.copy()
            if let tagStyle = self.currentTagView?.tagStyle {
                switchTagStyle(tagStyle)
                textInputView.tagStyleSelectView.select(style: tagStyle)
            }
            if let color = self.currentTagView?.color {
                textInputView.tagColorSelectView.select(color: color)
            }
            if let content = self.currentTagView?.text {
                textInputView.textView.text = content.yp.replacing("\n", with: "")
            }
        }
        setTextCount(textInputView.textView.text.count)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.frame.size = Wmc_screenSize
        // 键盘监听
        NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification).subscribe(onNext: { [weak self] noti in
            guard let weakSelf = self else { return }
            weakSelf.keyboardAction(notification: noti, hide: false)
        }).disposed(by: rx.disposeBag)

        // 键盘监听
        NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification).subscribe(onNext: { [weak self] noti in
            guard let weakSelf = self else { return }
            weakSelf.keyboardAction(notification: noti, hide: true)
        }).disposed(by: rx.disposeBag)

        // 关闭键盘管理
        keyboardManagerEnable = false
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textInputView.textView.becomeFirstResponder()
    }

    // Internal

    lazy var textInputView: WmcCreateTagInputView = {
        let inputView = WmcCreateTagInputView()
        return inputView
    }()

    lazy var textCountLabel: UILabel = {
        let label = UILabel.YP.Create(font: 14.yp.uiFont(weight: .medium), color: UIColor.white, alignment: .center)
        return label
    }()

    lazy var effectView: UIVisualEffectView = {
        let blurEffect = UIBlurEffect(style: .dark)
        let effectView = UIVisualEffectView(effect: blurEffect)
        effectView.alpha = 0.7
        return effectView
    }()

    var mode: Mode = .add

    var currentTagView: WmcBaseTagView?

    var textInputViewHeight: CGFloat = 160.wmc_autoVer

    var outputTageViewBlock: YPBlock.OneParam<WmcBaseTagView>?

    var deleteTageViewBlock: YPBlock.Empty?

    override func backAction() {
        dismissVC()
    }

    func keyboardAction(notification: Notification, hide: Bool) {
        guard let keyboardEndFrame = notification.yp.keyboardEndFrame,
              let keyboardAnimationDuration = notification.yp.keyboardAnimationDuration else { return }

        UIView.animate(withDuration: keyboardAnimationDuration,
                       delay: 0,
                       options: .curveEaseInOut) { [weak self] in
            guard let weakSelf = self else { return }
            let defaultY = Wmc_screenHeight - weakSelf.textInputViewHeight
            if hide { // 隐藏
                weakSelf.textInputView.frame = weakSelf.textInputView.frame.yp.set(y: defaultY - Wmc_safeAreaBottom)
            } else {
                weakSelf.textInputView.frame = weakSelf.textInputView.frame.yp.set(y: defaultY - keyboardEndFrame.size.height)
            }
        }
    }

    func switchTagStyle(_ tagStyle: WmcBaseTagView.TagStyle) {
        var showTagView: WmcBaseTagView = .init()
        switch tagStyle {
        case .tag:
            showTagView = WmcTagTagView()
        case .marked:
            showTagView = WmcMarkedTagView()
        case .textHookEdge:
            showTagView = WmcHookEdgeTextTagView()
        case .textBackground:
            showTagView = WmcTextBackgroundTagView()
        }
        showTagView.isFirstEdit = false
        // 参数继承
        if let text = currentTagView?.text {
            showTagView.text = text
        }
        showTagView.color = currentTagView?.color ?? .red
        // 选择器更迭

        showTagView.frame = CGRect(origin: .zero, size: showTagView.defaultSize)
        // 更迭视图
        currentTagView?.removeFromSuperview()
        view.insertSubview(showTagView, aboveSubview: effectView)
        currentTagView = showTagView
        currentTagView?.snp.remakeConstraints { make in
            make.centerX.equalToSuperview()
            var height = 140.wmc_autoVer
            if height > 140 {
                height = 140
            }
            make.centerY.equalTo(navView.snp.bottom).offset(height)
        }
    }

    /// 切换颜色
    func switchTagColor(_ color: WmcBaseTagView.Colors) {
        currentTagView?.color = color
    }

    func setTextCount(_ count: Int = 0) {
        if count == 100 {
            textCountLabel.text = "已达100字上限"
        } else {
            textCountLabel.text = "已输入\(count)/100字"
        }
    }

    func commitTagView() {
        // 判断是否需要返回标签
        if currentTagView?.text != currentTagView?.defaultText {
            currentTagView?.layoutIfNeeded()
            currentTagView?.sizeToFit()
            currentTagView?.defaultSize = currentTagView?.frame.size ?? .zero
            // 复制一份标签返回
            guard let tagView = currentTagView?.copy() else { return }
            outputTageViewBlock?(tagView)
        } else { // 无文案
            switch mode {
            case .add: break
            case .edit: // 编辑
                deleteTageViewBlock?() // 删除
            }
        }
        backAction()
    }

    override func makeUI() {
        view.backgroundColor = .clear

        addSubview(effectView)
        effectView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        makeNavView(style: .dark)
        title = "取消"

        navView.addSubview(textCountLabel)
        textCountLabel.snp.makeConstraints { make in
            make.centerY.height.equalTo(navView.backImageView)
            make.centerX.equalToSuperview()
        }

        addSubview(textInputView)
        textInputView.frame = CGRect(x: 0, y: Wmc_screenHeight - textInputViewHeight,
                                     width: Wmc_screenWidth, height: textInputViewHeight)
//        textInputView.snp.makeConstraints { make in
//            make.left.right.equalToSuperview()
//            make.bottom.equalTo(0)
//            make.height.equalTo(154)
//        }
    }

    override func bindViewAction() {
        textInputView.textDidChangeBlock = { [weak self] text in
            guard let weakSelf = self,
                  let text = text else { return }
            weakSelf.setTextCount(text.count)
            // 每隔10字插入1换行
            var count = 0
            var newText = ""
            for char in text {
                if count == 10 {
                    count = 0
                    newText.append("\n")
                }
                newText.append(char)
                count += 1
            }
            weakSelf.currentTagView?.text = newText
        }

        /// 编辑/输入完成
        textInputView.doneBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.commitTagView()
        }

        /// 切换颜色
        textInputView.tagColorSelectView.colorChangeSelectBlock = { [weak self] color in
            guard let weakSelf = self else { return }
            weakSelf.switchTagColor(color)
        }

        /// 切换样式
        textInputView.tagStyleSelectView.styleChangeSelectBlock = { [weak self] style in
            guard let weakSelf = self else { return }
            weakSelf.switchTagStyle(style)
        }
    }
}
